import { View, Image } from "@tarojs/components";
import { cva } from "class-variance-authority";
import { twMerge } from "tailwind-merge";
import ByText from "./ByText";
import { ensureCompleteUrl } from "@/utils";

const reg = /^[a-zA-z0-9]+$/;

type TByAvatarProps = {
  alt?: string;
  altLength?: number;

  circle?: boolean;
  src?: string;

  size?: number | string;
  className?: string;
};

export default ({
  src,
  alt = "",
  altLength = 2,
  size = 90,
  circle = true,
  className,
}: TByAvatarProps) => {
  const vars = cva(
    "inline-flex ovdeflow-hidden flex-none items-center justify-center rounded-3xl",
    {
      variants: {
        circle: {
          true: "rounded-full",
          false: "rounded-md",
        },
      },
    }
  );

  const getStylesheet = () => {
    if (size) {
      const val = typeof size == "number" ? `${size}rpx` : size;
      return `width: ${val};height: ${val}`;
    }
    return "";
  };

  const getAltText = () => {
    const length = alt?.length || 0;

    if (length <= altLength) {
      return alt;
    }

    const txt = alt.substring(length - 2, length);
    return reg.test(txt) ? alt.substring(0, length) : txt;
  };

  const altText = getAltText();

  const stylesheet = getStylesheet();

  return (
    <View className={twMerge(vars({ circle }), className)} style={stylesheet}>
      {src ? (
        <Image
          className="w-full h-full rounded-[inherit]"
          src={ensureCompleteUrl(src)}
        />
      ) : (
        <ByText>{altText}</ByText>
      )}
    </View>
  );
};
